// 代理模式
// 思想：当直接访问不满足需要的时候，提供一个代理对象来控制对对象的访问，替身对象对请求作出一些处理再转交给本体
// 例：缓存代理
const mult = function () {
  let a = 1
  console.log('mult调用了')
  for (let i = 0, l = arguments.length; i < l; i++) {
    a = a * arguments[i]
  }
  return a
}

const plus = function () {
  let a = 0
  console.log('plus调用了')
  for (let i = 0, l = arguments.length; i < l; i++) {
    a = a + arguments[i]
  }
  return a
}

/* 创建缓存代理的工厂 */
const createCacheProxy = function (fn) {
  const cache = {}
  return function () {
    const args = Array.prototype.join.call(arguments, ',')
    if (args in cache) {
      return cache[args]
    }
    return cache[args] = fn.apply(this, arguments)
  }
}


const proxyMult = createCacheProxy(mult)
const proxyPlus = createCacheProxy(plus)
console.log(proxyMult(3, 2))
console.log(proxyMult(4, 3))
console.log(proxyMult(3, 2))
console.log(proxyPlus(3, 2))
console.log(proxyPlus(9, 2))